<?php

	// ---------------------------
	// Set global vars
	// ---------------------------
	
	$accessLog = "access.log";
	$powerLog = "power.log";
	
	// ---------------------------
	// Get timestamp
	// ---------------------------
	
	$timeStamp = "[" . date("d/m/y H:i:s") . "]";
	
	// ---------------------------
	// Log access
	// ---------------------------
	
	// Open
	$accessHandle = fopen($accessLog, 'a+') or die("can't open access log file");
	
	// Write
	fwrite($accessHandle, $timeStamp . "\n");
	
	// Close
	fclose($accessHandle);

	// ---------------------------
	// Verify the user agent
	// ---------------------------
	
	if($_SERVER['HTTP_USER_AGENT'] != "WattsUp.NET"){
		die("User error.");
	}

	// ---------------------------
	// Parse and verify we got the required POST params
	// ---------------------------
	
	// Parse
	$meterId = $_POST['id'];
	$watts = $_POST['w'];
	$sendRate = $_POST['sr'];	
	
	// Verify
	if( ($meterId == "") || ($watts == "") || ($sendRate == "") ){
		die("Invalid parameters.");
	}

	// ---------------------------
	// Return the relay status [0] and optional send rate
	// ---------------------------
	
	// Build returncode
	$returnCode = "[0";
	if($sendRate != "1"){
		$returnCode .= "!1";
	}
	$returnCode .= "]";
	
	// Send
	echo $returnCode;

	// ---------------------------
	// Write power to file
	// ---------------------------
	
	// Format log line
	$logLine = $timeStamp . " ID: " . $meterId . " WATTS: " . $watts . "\n";
		
	// Open
	$powerHandle = fopen($powerLog, 'a+') or die("can't open power log file");
	
	// Write
	fwrite($powerHandle, $logLine);
	
	// Close
	fclose($powerHandle);

?>